import type { Channel, Articles } from '@/types/data'
import type { HomeAction } from '@/types/store'
import { sortBy } from 'lodash'

type HomeState = {
	//小写：大写（导入）
	userChannel: Channel[]
	restChannel: Channel[]
	channelActiveKey: string
	channelArticles: {
		[key: number]: Articles
	}
}

const initialState: HomeState = {
	userChannel: [],
	restChannel: [],
	channelActiveKey: '',
	channelArticles: {},
}

export const home = (state = initialState, action: HomeAction): HomeState => {
	switch (action.type) {
		case 'home/getUserChannel':
			return {
				...state,
				userChannel: action.payload,
				// 设置默认值
				channelActiveKey: action.payload[0]?.id + '',
			}

		case 'home/getAllChannel':
			return {
				...state,
				restChannel: action.payload,
			}

		//切换频道高亮
		case 'home/changeTab':
			return {
				...state,
				channelActiveKey: action.payload,
			}

		//删除频道
		case 'home/delChannel':
			return {
				...state,
				//删除当前频道
				userChannel: state.userChannel.filter(
					(item) => item.id !== action.payload.id
				),

				//将被删除频道添加到推荐
				restChannel: sortBy(
					[...state.restChannel, action.payload],
					'id'
				),
			}

		//添加频道
		case 'home/addChannel':
			return {
				...state,
				userChannel: [...state.userChannel, action.payload],
				restChannel: state.restChannel.filter(
					(item) => item.id !== action.payload.id
				),
			}

		// 频道文章列表数据
		case 'home/getChannelArticles':
			// 注意：当前频道的文章列表数据可能为空（比如，第一次加载），为了方便后续操作
			//  此处为其指定默认值
			const curChannelArticles = state.channelArticles[
				action.payload.channelId
			] ?? {
				pre_timestamp: null,
				results: [],
			}
			const {
				channelId,
				data: { pre_timestamp, results },
			} = action.payload

			return {
				...state,
				// 只修改：频道文章列表数据
				channelArticles: {
					...state.channelArticles,
					// 修改当前频道对应的文章列表数据
					[channelId]: {
						pre_timestamp,
						// 追加文章列表数据
						results: [
							// 已有数据
							// ...currentArticles.results,
							...curChannelArticles.results,
							// 接口返回的最新的文章列表数据
							...results,
						],
					},
				},
			}

		default:
			return state
	}
}
